package jogo.da.velha;

/**
 *
 * @author Guilherme Gaiardo
 */
public class Tabuleiro {
    private int[][] posicoes;
    private int tam;

    public Tabuleiro() {
        this.tam = 3;
        this.posicoes = new int[tam][tam];
        this.setaTabuleiro(this.tam);
    }

    public Tabuleiro(int tam) {
        this.tam = tam;
        this.posicoes = new int[tam][tam];
        this.setaTabuleiro(this.tam);
    }

    public void setaTabuleiro(int tam) {
        this.tam = tam;
        for (int i = 0; i < tam; i++)
            for (int j = 0; j < tam; j++)
                posicoes[i][j] = 0;
    }
    
    public int getPosicoes(int x, int y) {
        if (x >= 0 && x < 3 && y >= 0 && y < 3)
            return this.posicoes[x][y];
        System.out.printf("Bailo! %d %d %d", x, y, this.tam);
        System.exit(0);
        return 0;
    }

    public void setPosicoes(int x, int y, int id) {
        this.posicoes[x][y] = id;
    }
    
    public int marcaEm(int x, int y, int id)
    {
        if (this.jaTem(x,y) != 0)
            return 0;
        this.setPosicoes(x, y, id);
        return 1;
    }
    
    private int jaTem(int x, int y)
    {
        return this.posicoes[x][y];
    }
    
    public int verificaVitoria()
    {
        int i, j;
        int diagPin = this.getPosicoes(0, 0);
        if (this.getPosicoes(1, 1) == diagPin && this.getPosicoes(2, 2) == diagPin)
            return diagPin;
        
        int diagSec = this.getPosicoes(0, 2);
        if (this.getPosicoes(1, 1) == diagSec && this.getPosicoes(2, 0) == diagPin)
            return diagSec;
        
        int hor, ver;
        for (i=0; i<this.getTam(); i++)
        {
            hor = this.getPosicoes(i, 0);
            ver = this.getPosicoes(0, i);
            for (j=0; j<this.getTam(); j++)
            {
                if (this.getPosicoes(i, j) != hor)
                    hor = 0;
                if (this.getPosicoes(j, i) != ver)
                    ver = 0;
            }
            if (ver != 0)
                return ver;
            if (hor != 0)
                return hor;
        }
        return 0;
    }

    public int getTam() {
        return tam;
    }
}